from Exception_ import FgsException
import os
import os.path as path
import md5 as hasher

class Cache(object):
    def __init__(self, cache_root):
        self.cache_root = cache_root

        if (self.cache_enabled() and
            not path.exists(self.cache_root)):
            os.makedirs(self.cache_root)

    def cache_enabled(self):
        if not self.cache_root:
            return False
        else:
            return True

    def _get_file_path(self, filename):
        return path.join(self.cache_root, filename)

    def _calc_data_hash(self, data):
        return hasher.new(data).hexdigest()

    def store_file(self, data, data_hash=None):
        if not self.cache_enabled():
            return False

        file_hash = self._calc_data_hash(data)
        if data_hash and file_hash != data_hash:
            raise FgsException("Checksum mismatch")

        file_path = self._get_file_path(file_hash)

        f = file(file_path, 'wb')
        f.write(data)
        f.close()

        return file_hash

    def has_file(self, file_hash):
        if not self.cache_enabled():
            return False

        file_path = self._get_file_path(file_hash)
        if path.isfile(file_path):
            return True
        else:
            return False

    def retrieve_file(self, file_hash):
        if not self.has_file(file_hash):
            return False, None

        file_path = self._get_file_path(file_hash)

        f = file(file_path)
        data = f.read()
        f.close()

        return data

    def retrieve_file_path(self, file_hash):
        if not self.has_file(file_hash):
            return None

        return self._get_file_path(file_hash)
